package stack;

import java.util.Scanner;

public class MyStack {
    private static int len;
    private char[] arr;
    private int top;
    private boolean b = false;
    //建栈 设栈顶值top为-1时为栈空 确定栈的容量
    void buildstack(){
        top=-1;
        while (!b) {
            System.out.println("请输入栈容量：");
            Scanner sc = new Scanner(System.in);
            if (sc.hasNextInt()) {
                len = sc.nextInt();
                arr=new char[len];
                b = true;
                System.out.println("建栈成功");
            } else {
                System.out.println("输入类型错误，请输入数字。");
            }
        }
    }
    //控制台
    int controller(){
        int i;
        System.out.println("1:入栈 2:取栈顶 3:判断栈空 4:出栈 5:查找栈内元素 6:退出");
        System.out.println("请输入要执行的操作:");

        Scanner sc0 = new Scanner(System.in);
        if (sc0.hasNextInt()) {
            i = sc0.nextInt();
        } else {
            System.out.println("输入类型错误，请输入数字。");
            i=0;
        }
        return i;
    }
    //入栈操作 如果栈顶值top与栈容量相等则说明栈满，返回false意为入栈失败
    //        如果栈未满则入栈，栈顶值上移
    void pushstack(){
        System.out.println("请输入要插入的元素：");
        Scanner sc1 = new Scanner(System.in);
        char x = sc1.next().charAt(0);//问题1：没有nextchar可以直接接受字符
        if(top==len-1) {
            System.out.println("栈已满");
        }
        else {
            arr[++top] = x;
            System.out.println("入栈成功");
        }
    }
    //取栈顶元素
    void gettop() {
        if(top==-1){
            System.out.println("栈为空");
        }
        else System.out.println(arr[top]);
    }
    //判断栈空
    void stackempty(){
        boolean logic =(top == -1);
        System.out.println(logic);

    }
    //出栈操作
    void popstack(){
        if(top<0){
            System.out.println("栈已空");
        }
        else{
            char e=arr[top--];
            System.out.println(e);
        }
    }
    //查找 查找到则返回下标 未找到返回-1
    void search(){
        System.out.println("请输入要查找的元素：");
        Scanner sc2 = new Scanner(System.in);
        char x = sc2.next().charAt(0);
        int top1=top;
        while(top1>-1&&x!=arr[top1]){
            top1--;
        }
        if (top1==-1) {System.out.println("栈内无此元素");}
        else {System.out.println(x + "在栈中下标为：" + top1);}
    }
}
